package com.haust.swiper.config;

import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
public class MySpringCacheConfiguration {
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        //创建默认的缓存配置管理
        RedisCacheConfiguration configuration =
                RedisCacheConfiguration.defaultCacheConfig();

        //配置，可以提供
        configuration =
                configuration
                        .serializeKeysWith(
                                RedisSerializationContext.SerializationPair.fromSerializer(
                                        new StringRedisSerializer()
                                )
                        )
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(
                                new GenericJackson2JsonRedisSerializer()
                        ))
                        .entryTtl(Duration.ofMinutes(30L))
                        .disableCachingNullValues();

        //使用构建器 默认构建的管理器，是默认配置逻辑

        RedisCacheManager redisCacheManager=
                RedisCacheManager.create(factory)
                        .builder()
                        .cacheWriter(
                                RedisCacheWriter.lockingRedisCacheWriter(factory)
                        )
                        .cacheDefaults(configuration)
                        .build();
        return redisCacheManager;
    }
}
